<?php

namespace app\admin\controller\system;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use think\Env;

/**
 * 企业文化资料
 *
 * @icon fa fa-user
 */
class Company extends Backend
{


    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $models = null;
    protected $categorylist = [];
    private $redis;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\File;
        $this->redis = redis(Env::get('redis.host'), Env::get('redis.port'), Env::get('redis.pwd'), Env::get('redis.db'));
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                //->with(["users"=>['id','name'],"medic"=>['id','name'],"info"=>['id','name']])
                ->with([
                    'users' => function ($query) {
                        $query->withField('id,nickname');
                    },
                ])
                ->where($where)
                ->where('type',2)
                ->order('id', 'desc')
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                if (empty($params['name'])){
                    $this->error(__('资料名称不能为空'));
                }

                if (empty($params['url'])){
                    $this->error(__('文件不能为空'));
                }

                $params['admin_id'] = $this->auth->id;
                $params['type'] = 2;

                //var_dump($params);die();
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    /**
     * 详情
     */
    public function detail($ids)
    {

        $row = $this->model->get(['id' => $ids]);

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $row->image = explode(',',$row->url);
        $image = [];
        if (!empty($row->url)){
            foreach ($row->image as $k=>$v){
                $image[$k]['suffix'] = substr(strrchr($v, '.'), 1);
                $image[$k]['name'] = $v;
            }
        }

        $this->view->assign("row", $row);
        $this->view->assign("file", $image);
        return $this->view->fetch();
    }

}
